import {Builder} from "./builder/Builder";
import {Entity} from "./model/Entity";
import {DB} from "./db/DB";
import {SchemaTask} from "./task/SchemaTask";
import {Task} from "./task/Task";

const SchemaTask_key = 'schema';

export class Generator{
    config;
    builder: Builder;
    db: DB;
    constructor(rootPath, config){
        this.config = config;
        this.db = new DB(this.config.datasource)
        this.builder = new Builder(this.config, rootPath);
    }

    async getTasks() {
        let tables = await this.db.schema.getTables(this.db);
        if (tables) {
            let entitys = Entity.parseJson(tables, this.builder.configuration.strategy);
            this.builder.loadGenerateTarget(entitys);
        }
        if (this.builder.generateTargets.length === 0) return false;
        let tasks = [];
        for(let generateTarget of this.builder.generateTargets){
            if(!generateTarget.enable) continue;
            if(generateTarget.key === SchemaTask_key){
                tasks.push(new SchemaTask(generateTarget.path, SchemaTask.renderContent(tables), generateTarget.overridable));
            }else{
                tasks.push(new Task(
                    generateTarget.key,
                    generateTarget.path,
                    generateTarget.content,
                    generateTarget.overridable
                ));
            }
        }
        return tasks;
    }

    async generator() {
        let tasks = await this.getTasks();
        if(tasks && tasks.length > 0){
            for(let task of tasks){
                console.info('--------------------------- task: %s ---------------------------------', task.key)
                await task.execute();
                // console.info('\n')
            }
        }
    }
}
console.log()